package com.qc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.qc.dao.UserDateDao;
import com.qc.entity.BrowseEntity;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Repository("userDateDao")
public class UserDateDaoImpl implements UserDateDao{

	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public int saveBrowse(BrowseEntity browseEntity) {
		
		String sql = "insert into t_browse(user_id,receive_id)values(?,?)";
		
		return jdbcTemplate.update(sql,new Object[]{browseEntity.getUserId(),browseEntity.getReceiveId()});
	}
	
	@Override
	public int updateBrowse(BrowseEntity browseEntity) {
		
		String sql = "update t_browse set modified_time = CURRENT_TIMESTAMP where user_id = "+browseEntity.getUserId()+" and receive_id = " + browseEntity.getReceiveId();
		
		return jdbcTemplate.update(sql);
	}

	@Override
	public BrowseEntity getBrowseId(long userId, long receiveId) {

		String sql = "select IFNULL(user_id,0) user_id,receive_id from t_browse where user_id = "+userId+" and receive_id = "+receiveId+"";
		
		BrowseEntity browseEntity = new BrowseEntity();
        try {
        	browseEntity = (BrowseEntity) jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(BrowseEntity.class));
        } catch (DataAccessException e) {
        }
        
        return browseEntity;
	}

	@Override
	public List<BrowseEntity> listAllBrowse(long userId,long receiveId,int pageNo, int pageSize) {

		int beginRow = (pageNo - 1)* pageSize;
		
		String sql = "select a.b_id,"
				+ "	a.user_id,"
				+ "	a.receive_id,"
				+ " a.modified_time,"
				+ " b.avatar,"
				+ " b.nickname,"
				+ " b.user_age,"
				+ " b.sex,"
				+ " c.sec_height,"
				+ " c.job,"
				+ " c.live_province,"
				+ " c.b_name"
				+ " from t_browse a ";
		
				if ( userId != 0) {
					sql += " left join t_user b on b.user_id = a.receive_id ";
					sql += " left join t_user_secretary c on c.user_id = b.user_id";
					sql += " where 1 = 1";
				    sql += " and a.user_id = '"+userId+"' ";
				}
		
				if ( receiveId != 0) {
					sql += " left join t_user b on b.user_id = a.user_id ";
					sql += " left join t_user_secretary c on c.user_id = b.user_id";
					sql += " where 1 = 1";
				    sql += " and a.receive_id = '"+receiveId+"' ";
				}
		
			sql += " order by a.modified_time DESC ";
			sql += " LIMIT "+ String.valueOf(beginRow)+ "," + pageSize;
			
			return jdbcTemplate.query(sql, new BeanPropertyRowMapper(BrowseEntity.class));
	}


}
